<?php
namespace app\admin\controller;

use think\Controller;
use app\admin\model\Order as Orders;
use app\admin\model\Arctype;
use app\admin\model\ArctypeMod;
use think\Db;

class Order extends Common
{
    private $cModel;   //当前控制器关联模型
    
    public function _initialize()
    {
        parent::_initialize();
        $this->cModel = new Orders;   //别名：避免与控制名冲突
    }
    
    public function index()
    {
        $where = [];
        if (input('get.search')){
            $where['order_id'] = ['like', '%'.input('get.search').'%'];
        }
        if (input('get.parent')){
           $ids = Db::name('user')->where(['parent'=>input('get.parent')])->column('id');
           $where['uid'] = ['in',$ids];
        }
        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'id desc';
        }
        
        //是否是最高管理员
        if (session('userId')!=1) {
            $ids = Db::name('user')->where(['parent'=>session('userId')])->column('id');
            $where['uid'] = ['in',$ids];
        }

        $dataList = $this->cModel->where($where)->order($order)->paginate('', false, page_param());
        foreach ($dataList as $k => $v){
            $parentId = Db('user')->where('id',$v['uid'])->value('parent');
            $dataList[$k]['parent'] = Db('user')->where('id',$parentId)->value('name');
        }

        $salonSelect = $this->getSalonSelect(input('get.parent'),'form-control','','float:left;width: 146px');
        $this->assign('salonSelect', $salonSelect);
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }
    
    public function create($typeid){
        if (request()->isPost()){
            Db::startTrans();
            try{
                $data = input('post.');
                $data['create_time'] = strtotime($data['create_time']);
                if (isset($data['flag']) || isset($data['litpic'])){
                    $data['flag'] = $this->_flag($data['flag'], $data['litpic']);
                }
                $result = $this->cModel->validate(CONTROLLER_NAME.'.add')->allowField(true)->save($data);
                $data['aid'] = $this->cModel->getLastInsID();
                $mod = $data['mod'];
                $addonData = db($mod)->field('id', true)->strict(false)->insert($data);   //新增关联表数据
                // 提交事务
                if ($result && $addonData){
                    Db::commit();
                    return ajaxReturn(lang('action_success'), url('Arctype/index'));
                }else{
                    return ajaxReturn($this->cModel->getError());
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajaxReturn($e->getMessage());
            }
        }else{
            $atModel = new Arctype();
            $arctypeList = $atModel->treeList();
            $this->assign('arctypeList', $arctypeList);
            
            $arcData = $atModel->where(['id' => $typeid])->find();   //栏目数据
            $atmModel = new ArctypeMod();
            $where = [ 'id' => $arcData['mid'] ];
            $mod = $atmModel->where($where)->field('mod')->find();
            $mod = $mod['mod'];
            $this->assign('mods', $mod);   //文章拓展表模型
            
            $data['typeid'] = $arcData['id'];
            $data['create_time'] = date('Y-m-d H:i:s', time());
            $data['mid'] = $arcData['mid'];
            $this->assign('data', $data);
            
            return $this->fetch('edit');
        }
    }
    
    public function edit($id)
    {
        if (request()->isPost()){
            $data = input('post.');

            $result = $this->cModel->save($data, $data['id']);

            if ($result){
                return ajaxReturn(lang('action_success'), url('index'));
            }else{
                return ajaxReturn($this->cModel->getError());
            }
        }else{
            $atModel = new Arctype();
            $arctypeList = $atModel->treeList();
            $this->assign('arctypeList', $arctypeList);
            
            $data = $this->cModel->get($id);
            $addonMod = $data['mod'];
            $data['addondata'] = $data->$addonMod;   //拓展表数据
            unset($data[$data['mod']]);
            
            $atmModel = new ArctypeMod();
            $data['mid'] = $atmModel->where(['mod' => $addonMod])->value('id');
            
            $this->assign('mods', $addonMod);
            
            if (!empty($data['flag'])){
                $data['flag'] = explode(',', $data['flag']);
            }
            $this->assign('data', $data);
            return $this->fetch();
        }
    }
    
    public function delete()
    {
        if (request()->isPost()){
            $id = input('id');
            if (isset($id) && !empty($id)){
                $id_arr = explode(',', $id);
                if (!empty($id_arr)){
                    foreach ($id_arr as $val){
                        $this->cModel->where('id='.$val)->delete();
                    }
                    return ajaxReturn(lang('action_success'), url('index'));
                }else{
                    return ajaxReturn(lang('action_fail'));
                }
            }
        }
    }
    
    private function _flag($flag, $litpic)
    {
        if(empty($flag)){ $flag=array(); }
        if($litpic != ''){
            array_push($flag, "p");
        }else{
            $flag = unset_array("p", $flag);
        }
        $flag_arr = array_unique($flag);
        $result = implode(',', $flag_arr );
        return $result;
    }

    public function receipt(){
        if (request()->isPost()){
            $id = input('id');
            if (isset($id) && !empty($id)){
                $id_arr = explode(',', $id);
                if (!empty($id_arr)){
                    foreach ($id_arr as $val){
                        $addonMod = $this->cModel->where(['id' => $val])->update(['status'=>1]);
                        // $this->cModel->where('id='.$val)->delete();
                        // db($addonMod)->where('aid='.$val)->delete();   //关联表数据
                        
                        //更改订单状态回调未写
                        $changeorder = new \app\index\controller\Index;
                        $data = $this->cModel->where(['id' => $val])->find();
                        $changeorder->addMoney($data['uid'],$data['id']);
                        $changeorder->addScore($data['uid'],$data['id']);
                        $changeorder->changeVolume($data['id']);
                    }
                    return ajaxReturn(lang('action_success'), url('index'));
                }else{
                    return ajaxReturn(lang('action_fail'));
                }
            }
        }
    }



    public function pay(){
        if (!request()->isPost()) {
            if (session('userId')!=1) {
                $ids = Db::name('user')->where(['parent'=>session('userId')])->column('id');
                $where['id'] = ['in',$ids];
            }
            $where['user_type'] = 1;
            $where['status'] = 1;
            $users = Db('user')->where($where)->column('id,username');
            $products = Db('archive')->where(['status'=>1])->column('id,title');
            $this->assign('users', $users);
            $this->assign('products', $products);
            return $this->fetch();
        }else{
            
            $data = input('post.');
            if (!$data['number']) {
                return ajaxReturn(lang('action_fail'));
            }
            $data['order_id'] = date('Ymd').time().rand(1,9);
            $price = Db('archive')->where('id',$data['pid'])->value('price');
            $data['price'] = $price;
            $data['total'] = $data['number']*$price;
            $data['create_time'] = time();
            $result = Db::name('order')->insert($data);
            if ($result) {
                if ($data['pay_type']==1) {
                    $url = url('/weixin/'.Db::name('order')->getLastInsID());
                }
                if ($data['pay_type']==2){
                    $url = url('/aplay/'.Db::name('order')->getLastInsID());
                }
                return ajaxReturn(lang('action_success'), $url);
            }
            return ajaxReturn(lang('action_fail'));
        }
    }

    public function getSalonSelect($uid = false,$class=null,$id=0,$style="width:100%;"){
          $result = Db('user')->field('id,name')->where('id','<>',$id)->where('user_type','=','2')->select();
          
          $str = '<select name="parent" class="'.$class.'" style="'.$style.'"><option value="0">请选择美容院<option>';
          foreach ($result as $key => $val) {
            if ($uid==$val['id']) {
               $str .= '<option value="'.$val['id'].'" selected="selected">'.$val['name'].'<option>';
            }else{
               $str .= '<option value="'.$val['id'].'">'.$val['name'].'<option>';
            }
          }
          $str .= '</select>';
          return $str;
    }

}